package com.bj58.groupbuy.action.controllers;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.web.bind.ServletRequestUtils;

import com.bj58.groupbuy.action.charts.NullResult;
import com.bj58.groupbuy.action.interceptors.Check;
import com.bj58.groupbuy.action.model.ABTest;
import com.bj58.groupbuy.action.model.DisplayLocal;
import com.bj58.groupbuy.action.model.MSource;
import com.bj58.groupbuy.action.model.OperMenu;
import com.bj58.groupbuy.action.model.PCSource;
import com.bj58.groupbuy.action.model.PinDaoSource;
import com.bj58.groupbuy.action.model.SearchWordVo;
import com.bj58.groupbuy.action.model.TrafficUrlVo;
import com.bj58.groupbuy.action.model.User;
import com.bj58.groupbuy.action.service.DataReportService;
import com.bj58.groupbuy.action.service.DisplayLocalService;
import com.bj58.groupbuy.action.service.MSourceService;
import com.bj58.groupbuy.action.service.PCSourceService;
import com.bj58.groupbuy.action.service.PinDaoSourceService;
import com.bj58.groupbuy.action.service.UserOperService;
import com.bj58.groupbuy.action.service.impl.UserOperServiceImpl;
import com.bj58.groupbuy.action.util.ExcelUtil2;
import com.bj58.groupbuy.action.util.ExcelUtilNew;
import com.bj58.groupbuy.action.util.MyStore;
import com.bj58.groupbuy.action.util.ResourcesUtil;
import com.bj58.groupbuy.action.util.SomePublicUtil;
import com.bj58.groupbuy.action.util.StringUtil;
import com.bj58.groupbuy.action.util.TemplateMethodFactory;
import com.bj58.groupbuy.action.util.VelocityTools;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.groupbuy.wf.page.Paginate;
import com.bj58.wf.mvc.ActionResult;
import com.bj58.wf.mvc.BeatContext.Model;
import com.bj58.wf.mvc.MvcController;
import com.bj58.wf.mvc.actionresult.ContentResult;
import com.bj58.wf.mvc.annotation.GET;
import com.bj58.wf.mvc.annotation.POST;
import com.bj58.wf.mvc.annotation.Path;
import com.bj58.wf.mvc.client.RequestFile;
import com.google.common.collect.Lists;

/**
 * 数据统计报告下载
 * 
 * @author HL 2012.8.27
 */
@Path("datareport")
public class DataReportController extends MvcController {

	private final DataReportService dataReportService = ServiceLocator.get(DataReportService.class);
	private final SomePublicUtil spu = new SomePublicUtil();
	private final ExcelUtilNew eu = new ExcelUtilNew();
	private final DisplayLocalService displayLocalService = ServiceLocator.get(DisplayLocalService.class);
	
	
	/**
	 * 业务线搜索词数据下载
	 * 
	 * @return
	 */
	@Path("skwdata")
	@Check
	@POST
	@GET
	public ActionResult SKWdata() {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		try {
			String SkDate = ServletRequestUtils.getStringParameter(request, "startdate", "");
			String product = ServletRequestUtils.getStringParameter(request, "product", "");
			String city = ServletRequestUtils.getStringParameter(request, "filecity", "");
			String dpCateOne = ServletRequestUtils.getStringParameter(request, "dpCateOne", "");
			String dpCateTwo = ServletRequestUtils.getStringParameter(request, "dpCateTwo", "");
			String selecttype = ServletRequestUtils.getStringParameter(request, "typename", "");
			String platform =  ServletRequestUtils.getStringParameter(request, "platform", "pc");
			
			List<String> dpCateList = new ArrayList<String>();
			List<String> dpCateoneList = new ArrayList<String>();
			List<String> citynamelist = new ArrayList<String>();
			List<SearchWordVo> resultlist = new ArrayList<SearchWordVo>();
			List<String> cols = new ArrayList<String>();
			String excelTitle = "搜索词数据";
			excelTitle=SkDate+"-"+city+"-"+product+"-"+dpCateOne+"-"+dpCateTwo+"-"+excelTitle;
			cols.add("rank");
			cols.add("word");
			cols.add("wordCount");
			dpCateoneList.add("全部");
			dpCateList.add("全部");
			citynamelist.add("全部");
			List<DisplayLocal> cityList = displayLocalService.getLevelOne();// 一级城市
			for (int i = 0; i < cityList.size(); i++) {
				citynamelist.add(cityList.get(i).getLocalName());
			}
			model.add("cityList", citynamelist);

			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DATE, -1);
			String mapday = new SimpleDateFormat("yyyy-MM-dd").format(cal .getTime());

			dpCateList.add("黄页");
			dpCateList.add("房产");
			dpCateList.add("招聘");
			dpCateList.add("二手");
			dpCateList.add("二手车");
			dpCateList.add("二手创新");
			dpCateList.add("二手推广");
			
			model.add("platform", platform);
			model.add("product", "全部");
			model.add("dpCateOne", "全部");
			model.add("dpCateTwo", "全部");
			model.add("dpCateList", dpCateList);
			model.add("dpCateOneList", dpCateoneList);
			model.add("dpCateTwoList", dpCateoneList);

			if ("".equals(city))// 初始加载
			{	model.add("startdate", mapday);
			    model.add("filecity", "全部");	
				return ActionResult.view("stat/skwdatamain");
			}
			/*数据查询，PC端搜索词，作鑫开发, M端赵翔*/
			if(StringUtils.equalsIgnoreCase(platform, "pc")){//小于20151130的走之前的查询，否则走新查询
				if(SkDate.compareTo("2015-11-30")<0)
			   {
					if ("全部".equals(dpCateOne) && "全部".equals(city))// 全国热词下载，某个业务线top50热词下载、通过mysql查询
					{
						resultlist = dataReportService.getSearchWordDataFromSql(SkDate, product);
		
					} else {// 某个业务线下 即城市与业务线、类别的组合，通过hbase查询
						resultlist = dataReportService.getSearchWordDataFromHbase(
								SkDate, product, city, dpCateOne, dpCateTwo);
					}
			   }else {
				   resultlist= dataReportService.getSearchWordDataFromHbase_M(SkDate, product, city, dpCateOne, dpCateTwo,"pc");
			   }
			}else if(StringUtils.equalsIgnoreCase(platform, "m")){
				resultlist = dataReportService.getSearchWordDataFromHbase_M(SkDate, product, city, dpCateOne, dpCateTwo,"m");
			}
			/*  查询   */
			if("".equals(selecttype))
			{
				model.add("startdate", SkDate);
			    model.add("filecity", city);
				model.add("product", product);
				model.add("dpCateOne", dpCateOne);
				model.add("dpCateTwo", dpCateTwo);
				//重新加载复选框
				if(!"全部".equals(product))
				{
					List<String> dpCate1List = new ArrayList<String>();
					dpCate1List=dataReportService.getCate1List(product);
					model.add("dpCateOneList", dpCate1List);
					if(!"全部".equals(dpCateOne))
					{
						List<String> dpCate2List = new ArrayList<String>();
						dpCate2List=dataReportService.getCate2List(product,dpCateOne);
						model.add("dpCateTwoList", dpCate2List);
					}				
				}
				int len = resultlist.size();
				if (len > 25) {
					for (int i = 0; i + 25 < len; i++) {
						resultlist.get(i)
								.setRank2(resultlist.get(i + 25).getRank());
						resultlist.get(i)
								.setWord2(resultlist.get(i + 25).getWord());
						resultlist.get(i).setWordCount2(
								resultlist.get(i + 25).getWordCount());
					}
					model.add("rsList", resultlist.subList(0, 25));
				}else {
					model.add("rsList", resultlist);
				}
			
			}else {	/*  下载   */
				 ExcelUtil2<SearchWordVo> u = new
				 ExcelUtil2<SearchWordVo>(SearchWordVo.class);
				 u.setFieldFilter(cols);
				 u.createExcelFileAndDownload(resultlist, excelTitle);
				 return new ContentResult("");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ContentResult("error");
		}
		return ActionResult.view("stat/skwdatamain");
	}
	/**
	 * 运营URL流量查询
	 * 
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@Path("trafficUrl")
	@POST
	@GET
	public ActionResult trafficUrlData() {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		try {
			/**获取日期*/
			String StartDate = ServletRequestUtils.getStringParameter(request, "startDate", "");
			String EndDate = ServletRequestUtils.getStringParameter(request, "endDate", "");
			/**获取维度*/
			String statdateCombine = ServletRequestUtils.getStringParameter(request, "statdateCombine", "");
			String sourceCombine = ServletRequestUtils.getStringParameter(request, "sourceCombine", "");
			String clicktagCombine = ServletRequestUtils.getStringParameter(request, "clicktagCombine", "");
			/**获取查询方式*/
			String queryway = ServletRequestUtils.getStringParameter(request, "queryway", "");
			String selecttype = ServletRequestUtils.getStringParameter(request, "typename", "");
			/**获取url*/
			String URLname =  ServletRequestUtils.getStringParameter(request, "URLname", "");
			/**获取页码*/
			int pageindex = ServletRequestUtils.getIntParameter(request,"pageindex",1);//页数。
			int beginpagenum=(pageindex-1)*20;
			int endpagenum=beginpagenum+20;
			StringBuffer url =new StringBuffer();//分页的URL
			int count=0;
		    url.append("&startDate="+StartDate);
		    url.append("&endDate="+EndDate);
		    url.append("&queryway="+queryway);
		    url.append("&URLname="+URLname);
		    url.append("&typename="+selecttype);
			if("".equals(StartDate)||"".equals(EndDate)||"".equals(URLname))
			{
				return ActionResult.view("stat/trafficforurl");
			} 
			String statdate="";
			String conditions="";
			int sub=0;
			StringBuffer groupby=new StringBuffer();
			Map<String,String> tempMap=new HashMap<String, String>();
			Map<String,String> FormulaMap=new HashMap<String, String>();
			if(URLname.contains("?"))
			{
				String a[]={};
				a=URLname.split("\\?");
				URLname=a[0];
			}
			List<String> cols = new ArrayList<String>();
			StringBuffer sumlines=new StringBuffer();
			sumlines.append("sum(pv),sum(uv)");//对涉及公式的通过下标来计算
			FormulaMap.put("pv", String.valueOf(sub++));
			FormulaMap.put("uv", String.valueOf(sub++));
			String month1=StartDate.substring(0, 4);
			String month2=EndDate.substring(0, 4);
		    if(!month1.equals(month2))//如果时间维度跨月
			{
		    	conditions="wherefordate and url";
		    	statdate="startdate:"+StartDate+";enddate:"+EndDate+";beginnum:"+beginpagenum+";endnum:"+endpagenum;
			}else
			{
				conditions="stat_date<='"+EndDate+"' and stat_date>='"+StartDate+"' and url";
			}
			String selectdate="";
			model.add("startDate", StartDate);
			model.add("endDate", EndDate);
			model.add("statdateCombine", statdateCombine);
			model.add("sourceCombine", sourceCombine);
			model.add("clicktagCombine", clicktagCombine);
			model.add("URLname", URLname);
			List<TrafficUrlVo> resultlist = new ArrayList<TrafficUrlVo>();
			if("".equals(queryway))
			    model.add("queryway", "jingque");
			else
				model.add("queryway", queryway);
		    if("jingque".equals(queryway))
		    {
		    	conditions=conditions+" = '"+URLname+"'";
		    }else
		    {
		        conditions=conditions+" like '"+URLname+"%'";
		    }    
            if("stat_date".equals(statdateCombine))
            {
            	conditions=conditions+" GROUP BY stat_date";
            	groupby.append("stat_date");
            	cols.add("stat_date");
            	selectdate="yes";
            	statdate +=";selectdate:"+selectdate;
            	url.append("&statdateCombine="+statdateCombine);
            }
            if("source".equals(sourceCombine))
            {
            	//lines=lines+",source,source_pv,source_ctr";
            	sumlines.append(",sum(source_pv)");
            	FormulaMap.put("source_pv", String.valueOf(sub++));
            	FormulaMap.put("source_ctr",FormulaMap.get("pv")+"/"+FormulaMap.get("source_pv"));
            	cols.add("source");
            	cols.add("source_pv");
            	cols.add("source_ctr");
            	if(conditions.contains("GROUP BY"))
            	{	conditions=conditions+",source";
            	    groupby.append(",source");
            	}
            	else
            	{
            		groupby.append("source");
            		conditions=conditions+" GROUP BY source";
            	}
            	url.append("&sourceCombine="+sourceCombine);
            	
            }
            if("click_tag".equals(clicktagCombine))
            {
            	sumlines.append(",sum(click)");
            	FormulaMap.put("click", String.valueOf(sub++));
            	cols.add("click_tag");
            	cols.add("click");
            	cols.add("click_ctr");
            	FormulaMap.put("click_ctr",FormulaMap.get("click")+"/"+FormulaMap.get("pv"));
            	if(conditions.contains("GROUP BY"))
            	{
            		conditions=conditions+",click_tag";
            		groupby.append(",click_tag");
            	}
            	else
            	{
            		groupby.append("click_tag");
            		conditions=conditions+" GROUP BY click_tag";
            	}
            	url.append("&clicktagCombine="+clicktagCombine);
            }else
            {
            	sumlines.append(",sum(click)");
            	FormulaMap.put("click", String.valueOf(sub++));
            	cols.add("click");
            }
            
            if(!month1.equals(month2))//如果时间维度跨年
			{
            	ArrayList<String> rsArrayList=new ArrayList<String>();
            	if("stat_date".equals(statdateCombine))//如果分组中有日期维度
            	{
            		Map<Integer,List<TrafficUrlVo>> rsMap=new HashMap<Integer, List<TrafficUrlVo>>();
            		if("".equals(selecttype))//查询时数据
            		{
            		   rsMap=dataReportService.getHasDateForsql(conditions, statdate,"");
            		}else//下载时数据
            		 {
            		   rsMap=dataReportService.getHasDateForsql(conditions, statdate,"true");
					}
            		Iterator iter = rsMap.entrySet().iterator();
            		if(iter.hasNext())
            		{
            			Map.Entry entry = (Map.Entry) iter.next();
            			count=Integer.parseInt(entry.getKey().toString());
            			resultlist=rsMap.get(count);
            		}
            	}else {				
		            	tempMap=dataReportService.getTrafUrlDataForYear(groupby.toString(), conditions, sumlines.toString(),statdate);
		            	Iterator iter = tempMap.entrySet().iterator();
		            	if("".equals(selecttype))//查询时处理本页数据
	            		{
			            	int countiter=0;
			            	while (countiter<beginpagenum&&iter.hasNext()) {//无日期组合查询时只根据页码计算相应的数据
								countiter++;
								iter.next();
							}
			            	while(iter.hasNext()&&countiter<endpagenum) {//遍历组合后的结果值
				            	Map.Entry entry = (Map.Entry) iter.next();
				            	StringBuffer newvalBuffer=new StringBuffer();
				            	String key = entry.getKey().toString();
				            	String[] keycolname=key.split("#");
				            	String[] groupname=groupby.toString().split(",");
				            	if(!"".equals(groupby.toString()))
					            {  for(int i=0;i<keycolname.length;i++)
					            	{
					            		newvalBuffer.append(groupname[i]+":"+keycolname[i]+"@");
					            	}
					            }
				            	String oldval = entry.getValue().toString();
				            	String[] tempdata=oldval.split("\\$");
				            	
				            	Iterator itercols = FormulaMap.entrySet().iterator();
				            	while(itercols.hasNext()) {//对每个属性值进行计算
					            	Map.Entry entrycols = (Map.Entry) itercols.next();
					            	String oldvalcols = entrycols.getValue().toString();
					            	String keycols = entrycols.getKey().toString();
					            	if(oldvalcols.contains("/"))
					            	{
					            		String[] subcols=oldvalcols.split("/");
					            		String s1=tempdata[Integer.parseInt(subcols[0])];
					            		String s2=tempdata[Integer.parseInt(subcols[1])];
					            		String s3=StringUtil.StrSubstr(s1, s2);
					            		if(s3.length()>8&&(!s3.contains("E")))
					            		  s3=s3.substring(0,8);//控制ctr位数
					            		newvalBuffer.append(keycols+":"+s3+"@");
					            	}else {
					            		newvalBuffer.append(keycols+":"+tempdata[Integer.parseInt(oldvalcols)]+"@");
									}
				            	}
				            	String finalstring=newvalBuffer.toString();
				            	rsArrayList.add(finalstring.substring(0, finalstring.length()-1));//去掉最后一个@
				            	countiter++;
			            	   }
			            	//放到service里面，return回去
			            	resultlist= dataReportService.getTrafUrlDataFromString(rsArrayList);
			            	count=tempMap.size();
	            		}else {//下载时处理所有的数据
	            			while(iter.hasNext())
	            			{
	            				Map.Entry entry = (Map.Entry) iter.next();
				            	StringBuffer newvalBuffer=new StringBuffer();
				            	String key = entry.getKey().toString();
				            	String[] keycolname=key.split("#");
				            	String[] groupname=groupby.toString().split(",");
				            	for(int i=0;i<keycolname.length;i++)
				            	{
				            		newvalBuffer.append(groupname[i]+":"+keycolname[i]+"@");
				            	}
				            	String oldval = entry.getValue().toString();
				            	String[] tempdata=oldval.split("\\$");
				            	
				            	Iterator itercols = FormulaMap.entrySet().iterator();
				            	while(itercols.hasNext()) {//对每个属性值进行计算
					            	Map.Entry entrycols = (Map.Entry) itercols.next();
					            	String oldvalcols = entrycols.getValue().toString();
					            	String keycols = entrycols.getKey().toString();
					            	if(oldvalcols.contains("/"))
					            	{
					            		String[] subcols=oldvalcols.split("/");
					            		String s1=tempdata[Integer.parseInt(subcols[0])];
					            		String s2=tempdata[Integer.parseInt(subcols[1])];
					            		String s3=StringUtil.StrSubstr(s1, s2);
					            		if(s3.length()>8&&(!s3.contains("E")))
					            		  s3=s3.substring(0,8);//控制ctr位数
					            		newvalBuffer.append(keycols+":"+s3+"@");
					            	}else {
					            		newvalBuffer.append(keycols+":"+tempdata[Integer.parseInt(oldvalcols)]+"@");
									}
				            	}
				            	String finalstring=newvalBuffer.toString();
				            	rsArrayList.add(finalstring.substring(0, finalstring.length()-1));//去掉最后一个@
				            	resultlist= dataReportService.getTrafUrlDataFromString(rsArrayList);
	            			}
						}
				}
			}else{//单表查询
				count=dataReportService.getTrafUrlDataForCount(conditions);//计算总数
				if("".equals(selecttype))
				{
				conditions=conditions+" LIMIT "+beginpagenum+","+20+"";
				}				
				String year=StartDate.substring(0,4);
				resultlist=dataReportService.getTrafUrlDataFromSql(year, conditions);
			}
           
            /** 查询   */
			if("".equals(selecttype))
			{
			 if(!"".equals(groupby.toString()))
			 {
				 Paginate<String> pList = new Paginate<String>(count,pageindex,20,null);
		         model.add("pList",pList);
		         model.add("paramurl",url.toString());
			 }else {
				 Paginate<String> pList = new Paginate<String>(1,1,20,null);
		         model.add("pList",pList);
			}
			 model.add("rsList", resultlist);	
			}else {	/**下载*/
				 String excelTitle=StartDate+"-"+EndDate+"运营URL流量查询结果";
				 cols.add("pv");
				 cols.add("uv");
				 ExcelUtil2<TrafficUrlVo> u = new
				 ExcelUtil2<TrafficUrlVo>(TrafficUrlVo.class);
				 u.setFieldFilter(cols);
				 u.createExcelFileAndDownload(resultlist, excelTitle);
				 return new ContentResult("");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ContentResult("error");
		}
		return ActionResult.view("stat/trafficforurl");
	}	
	/**
	 * PC,无线来源数据上传
	 * 
	 * @param option
	 * @return
	 */
	@Path("upload/{option}")
	@POST
	@GET
	public ActionResult AllianceManager(String option) {
		Model model = beat.getModel();
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class, model);
		String returnUrl = "ors/uploadMSource";
		String result = "";
		try {
			if ("toupload_M".equals(option)) {
				returnUrl = "ors/uploadMSource";
			} else if ("toupload_PC".equals(option)) {
				returnUrl = "ors/uploadPCSource";
			}  else if ("toupload_PingDao".equals(option)) {
				returnUrl = "ors/uploadPinDaodata";
			} else if ("upload_M".equals(option)) {
				RequestFile file = beat.getClient().getUploads().getFile("MSourceFile");
				// BufferedReader reader=new BufferedReader(new InputStreamReader(file.getInputStream(),"UTF-8"));
				String fileType = file.getContentType();
				returnUrl = "ors/uploadMSource";
				if (file.getSize() > 0) {
					List<String> ecList = null;
					if (fileType!=""&&fileType.contains("application/vnd")) {
						ecList = ExcelUtilNew.readExcel(file.getInputStream(),file.getOriginalFilename());
						ecList.remove(0); // 去掉表头
					} else if ("text/plain".equals(fileType)) {
						ResourcesUtil.setCharset(Charset.forName("UTF-8"));
						ecList = ResourcesUtil.readAsList(file.getInputStream());
					} else {
						model.add("message", "error");
						return ActionResult.view(returnUrl);
					}
					MSourceService msService = ServiceLocator.get(MSourceService.class);
					boolean res = msService.dealMSourceData(ecList);
					if (res == true) {
						result = "success";
					} else {
						result = "error";
					}
				}
			} else if ("upload_PC".equals(option)) {
				RequestFile file = beat.getClient().getUploads().getFile("PCSourceFile");
				String fileType = file.getContentType();
				returnUrl = "ors/uploadPCSource";
				if (file.getSize() > 0) {
					List<String> ecList = null;
					if (fileType!=""&&fileType.contains("application/vnd")) {
						ecList = ExcelUtilNew.readExcel(file.getInputStream(),file.getOriginalFilename());
						ecList.remove(0); // 去掉表头
					} else if ("text/plain".equals(fileType)) {
						ResourcesUtil.setCharset(Charset.forName("UTF-8"));
						ecList = ResourcesUtil.readAsList(file.getInputStream());
					} else {
						model.add("message", "error");
						return ActionResult.view(returnUrl);
					}
					PCSourceService msService = ServiceLocator.get(PCSourceService.class);
					boolean res = msService.dealPCSourceData(ecList);
					if (res == true) {
						result = "success";
					} else {
						result = "error";
					}
				}
				
			}else if ("upload_PingDao".equals(option)) {//频道数据上传
				RequestFile file = beat.getClient().getUploads().getFile("PinDaoSourceFile");
				String fileType = file.getContentType();
				returnUrl = "ors/uploadPinDaodata";
				if (file.getSize() > 0) {
					List<String> ecList = null;
					if (fileType!=""&&fileType.contains("application/vnd")) {//"application/vnd.ms-excel".equals(fileType)
						ecList = ExcelUtilNew.readExcel(file.getInputStream(),file.getOriginalFilename());
						ecList.remove(0); // 去掉表头
					} else if ("text/plain".equals(fileType)) {
						ResourcesUtil.setCharset(Charset.forName("UTF-8"));
						ecList = ResourcesUtil.readAsList(file.getInputStream());
					} else {
						model.add("message", "error");
						return ActionResult.view(returnUrl);
					}
					PinDaoSourceService msService = ServiceLocator.get(PinDaoSourceService.class);
					boolean res = msService.dealPinDaoSourceData(ecList);
					if (res == true) {
						result = "success";
					} else {
						result = "error";
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = "error";
		}
		model.add("message", result);
		return ActionResult.view(returnUrl);
	}

	/**
	 * PC,无线来源数据下载
	 * 
	 * @param option
	 * @return
	 */
	@Path("download/{option}")
	@POST
	@GET
	public ActionResult downloadSourceData(String option) {
		HttpServletRequest request = beat.getRequest();
		HttpServletResponse response = beat.getResponse();
		try {
			List<String> colDicList = null;
			List<String> titleList = new ArrayList<String>(); // 表头名
			if ("download_M".equals(option)) {
				MSourceService msService = ServiceLocator.get(MSourceService.class);
				List<MSource> allData = msService.getAllList();
				colDicList = spu.getECDicByAnnotation(MSource.class);
				for (String colDic : colDicList) {
					String colCname = colDic.split(",")[1];
					titleList.add(colCname + ":0");
				}
				List<String> finaList = eu.tranVoToString(MSource.class, allData, null, null);
				SXSSFWorkbook wwb = ExcelUtilNew.writeExcelCommonForIR("无线来源数据", response, titleList, finaList, "");
				ExcelUtilNew.downLoadExcel(request, response, "无线来源数据", wwb);
			} else if ("download_PC".equals(option)) {
				PCSourceService pcService = ServiceLocator.get(PCSourceService.class);
				List<PCSource> allData = pcService.getAllList();
				colDicList = spu.getECDicByAnnotation(PCSource.class);
				for (String colDic : colDicList) {
					String colCname = colDic.split(",")[1];
					titleList.add(colCname + ":0");
				}
				List<String> finaList = eu.tranVoToString(PCSource.class, allData, null, null);
				SXSSFWorkbook wwb = ExcelUtilNew.writeExcelCommonForIR("PC来源数据", response, titleList, finaList, "");
				ExcelUtilNew.downLoadExcel(request, response, "PC来源数据", wwb);
			} else if ("download_pingdao".equals(option)) {
				
				PinDaoSourceService msService = ServiceLocator.get(PinDaoSourceService.class);
				List<PinDaoSource> allData = msService.getAllList();
				colDicList = spu.getECDicByAnnotation(PinDaoSource.class);
				for (String colDic : colDicList) {
					String colCname = colDic.split(",")[1];
					titleList.add(colCname + ":0");
				}
				List<String> finaList = eu.tranVoToString(PinDaoSource.class, allData, null, null);
				SXSSFWorkbook wwb = ExcelUtilNew.writeExcelCommonForIR("频道来源数据", response, titleList, finaList, "d:/");
				ExcelUtilNew.downLoadExcel(request, response, "频道来源数据", wwb);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ContentResult("下载失败");
		}
		return new NullResult();
	}
	
	

	public static final JSONObject pageMap = JSONObject.fromObject("{index:'大类页',list:'列表页',detail:'详情页',post:'发布页',home:'首页'}");
	
	/**
	 * A/B测试版本管理
	 * 
	 * @return
	 */
	@Path("abtest")
	@Check("datareport/abtest")
	@POST
	@GET
	public ActionResult abTestData() {
		HttpServletRequest request = beat.getRequest();		
		Model model = beat.getModel();	
		try {
								
			User user = spu.getUserByCookie(request);		
			//检查业务线权限
			String[] businessOper = businessOperCheck(user).split(",");
			List<String> businessOpers = Lists.newArrayList();
			for(String i:businessOper)
			{
				businessOpers.add(i);					
			}
			String businessline = ServletRequestUtils.getStringParameter(request, "businessline",businessOpers.get(0));
			
			List<String> pagelist = Lists.newArrayList();//根据第一个权限 展示pagelist
			if("total".equals(businessline))
			{
				pagelist.add("home");
			}
			else
			{
				pagelist.add("index");
				pagelist.add("list");
				pagelist.add("detail");
				pagelist.add("post");
			}
			
			//获取业务线  页面类型 平台				
			String pagetype = ServletRequestUtils.getStringParameter(request, "pagetype", "");					
			String platform = ServletRequestUtils.getStringParameter(request, "platform", "");		
			
			model.add("businessline", businessline);
			model.add("businessList", businessOpers);
			model.add("business_CN_Map", EnumCate.business_CN_Map);	
			model.add("pagelist", pagelist);
			model.add("pageMap", pageMap);	
			
			//查询or添加
			String selecttype = ServletRequestUtils.getStringParameter(request, "selecttype", "");		
			//获取页码
			int pageindex = ServletRequestUtils.getIntParameter(request,"pageindex",1);
			int beginpagenum=(pageindex-1)*20;
		
			if("".equals(selecttype))// 初始 
			{
				return ActionResult.view("stat/abtest");
			} 			                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
			if("query".equals(selecttype))// 查询           
			{
				StringBuffer url = new StringBuffer(); //分页查询参数				
				url.append("&businessline="+businessline);
				url.append("&pagetype="+pagetype);
				url.append("&platform="+platform);
				url.append("&selecttype="+selecttype);
				
				//分页查询
				int count =0;		
				count=dataReportService.getABTestDataForCount(businessline,pagetype,platform);	//计算总条数
		
				List<ABTest>resultlist = new ArrayList<ABTest>();
				
				String condition = " LIMIT "+beginpagenum+","+20+"";
				resultlist=dataReportService.getABTestDataFromSql(businessline,pagetype,platform,condition);		
				
				Paginate<String> pList = new Paginate<String>(count,pageindex,20,null);
		        model.add("pList",pList);
		        model.add("paramurl",url.toString());
		         
		        model.add("rsList", resultlist);
		        model.add("pageindex",pageindex);
		        model.add("pagetype",pagetype);
		        model.add("platform",platform);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ContentResult("error");
		}
		return ActionResult.view("stat/abtest");
	}
	
	/**
	 * A/B测试版本管理    状态切换 添加
	 * 
	 * @return
	 */
	@Path("abtest/{option}")
	@POST
	@GET
	public ActionResult abTestState(String option) {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();	
		try {
			
			if("add".equals(option)){ 
			
				//获取业务线  页面类型 平台
				String businessline = ServletRequestUtils.getStringParameter(request, "businessline", "");					
				String pagetype = ServletRequestUtils.getStringParameter(request, "pagetype", "");					
				String platform = ServletRequestUtils.getStringParameter(request, "platform", "");	
				
				String creater = spu.getUserByCookie(request).getUsername();
				//获取备注
				String  mark=  ServletRequestUtils.getStringParameter(request, "mark", "");
	
				int r;
				r=dataReportService.insertABTestDataFromSql(businessline,pagetype,platform,creater,mark);	
				
				if(r==0){
					return new ContentResult("error");
				}else{
					return new ContentResult("success");
				}
			}else if("search".equals(option)){ 
			
				//获取搜索项
				String  creater=  ServletRequestUtils.getStringParameter(request, "creater", "");
				
				int pageindex = ServletRequestUtils.getIntParameter(request,"pageindex",1);
				int beginpagenum=(pageindex-1)*20;
	
				StringBuffer url = new StringBuffer(); //分页查询参数	
				url.append("&creater="+creater);
				
				//分页查询
				int count =0;		
				count=dataReportService.getABTestCountByCreater(creater);//计算总条数
		
				List<ABTest>resultlist = new ArrayList<ABTest>();
				
				String condition = " LIMIT "+beginpagenum+","+20+"";
				resultlist=dataReportService.getABTestDataByCreater(creater,condition);		
				
				Paginate<String> pList = new Paginate<String>(count,pageindex,20,null);
		        model.add("pList",pList);
		        model.add("paramurl",url.toString());		         
		        model.add("rsList", resultlist);
		        model.add("pageindex",pageindex);
		          
		        User user = spu.getUserByCookie(request);		
				//检查业务线权限
				String[] businessOper = businessOperCheck(user).split(",");
				List<String> businessOpers = Lists.newArrayList();
				for(String i:businessOper)
				{
					businessOpers.add(i);					
				}
				String businessline = ServletRequestUtils.getStringParameter(request, "businessline",businessOpers.get(0));
				
				List<String> pagelist = Lists.newArrayList();//根据第一个权限 展示pagelist
				if("total".equals(businessline))
				{
					pagelist.add("home");
				}
				else
				{
					pagelist.add("index");
					pagelist.add("list");
					pagelist.add("detail");
					pagelist.add("post");
				}							
				model.add("businessline", businessline);
				model.add("businessList", businessOpers);
				model.add("business_CN_Map", EnumCate.business_CN_Map);	
				model.add("pagelist", pagelist);
				model.add("pageMap", pageMap);	
				
		        return ActionResult.view("stat/abtest");
			}	
		}catch (Exception e) {
			e.printStackTrace();
			return new ContentResult("error");
		}
		return new ContentResult("error");
	}
		
	public enum EnumCate {
		total, zhaopin, fangchan, huangye, ershou, ershouche;
		public static final JSONObject business_CN_Map = JSONObject.fromObject("{zhaopin:'招聘',fangchan:'房产',huangye:'黄页',ershou:'二手',ershouche:'二手车',total:'全站'}");
	
	}
	
	private static UserOperService userOperService = new UserOperServiceImpl();
	
	/**业务线细粒度权限检查
	 */
	public static String businessOperCheck(User user)throws Exception{
		String operShowBusi = ""; 
		if(MyStore.admin.equals(user.getFunction())){	//管理员权限
			return "total,zhaopin,fangchan,huangye,ershou,ershouche";
		}else{ 
			HashSet<Long> userOpersSet = userOperService.getUserOpers(user.getId());//用户全部细粒度权限
			List<OperMenu> operList = userOperService.getOperListByCate("全局控制", "业务线权限"); //该系列所有正常数据权限
			for (OperMenu operMenu : operList) { //如果用户细粒度权限中没有此类权限约束  即不做控制处理
				long operId = operMenu.getId();
				if(userOpersSet.contains(operId)){
					if(operId == 12){ //全部业务线权限
						return "total,zhaopin,fangchan,huangye,ershou,ershouche";
					}else{
						String name  = operMenu.getName();
						if(EnumCate.business_CN_Map.containsKey(name))
							operShowBusi = operShowBusi +operMenu.getName()+",";
					}
				}
			}
			if(operShowBusi.length()>0){
				operShowBusi = operShowBusi.substring(0,operShowBusi.lastIndexOf(","));
				if(operShowBusi.split(",").length >= 5){	//全部业务线权限
					return "total,zhaopin,fangchan,huangye,ershou,ershouche";
				}
			}
		}
		
		return operShowBusi;
	}
}
